package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

@Controller
@RequestMapping("/houtai")
public class HouTaiController {
    @Autowired
    AccountService accountService;
    @Autowired
    OrderService orderService;
    @Autowired
    CatalogService catalogService;

    @Autowired
    CatalogService catalogService1;

    @Autowired
    CatalogService catalogService2;

    @Autowired
    CatalogService catalogService3;

    @Autowired
    CatalogService catalogService4;


    @GetMapping("/productManage")
    public String productManage(Model model){
        model.addAttribute("productList",catalogService.getProductListByCategory("DOGS"));
        return "houtai/productManage";
    }

    @GetMapping("/general")
    public String general(Model model) {
        Account account=accountService.getAccount("zcs","202cb962ac59075b964b07152d234b70");
        String username=account.getUsername();
        List<Order> orderList = orderService.getOrderList();
        System.out.println("id=" + orderList.get(0).getOrderId());
        model.addAttribute("orderList", orderList);
        Order order= orderService.getOrder(1151);
        order.setOrderId(0);
        order.setShipAddress1("null");
        order.setBillAddress1("null");
        order.setShipCountry("null");
        BigDecimal bigDecimal=new BigDecimal("0.00");
        order.setTotalPrice(bigDecimal);
        model.addAttribute("changeOrder",order);
        return "houtai/general";
    }

    @GetMapping("/basic_form")
    public String basic_form(Model model){
        model.addAttribute("AccountList",accountService.getAccountList());
        return "houtai/basic_form";
    }

    @GetMapping("/test")
    public String signonForm() {
        return "houtai/test";
    }

    @GetMapping("/simple")
    public String simple() {
        return "houtai/simple";
    }


    //****登录检测****//
    @PostMapping("/signonCheck")
    public String signonCheck(HttpServletRequest req,
                              @RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("memPhone") String memPhone,
                              @RequestParam("vCode") String vCode, Model model) throws Exception {
//        Account account = accountService.getAccount(username, password);
        String md5pass = DigestUtils.md5DigestAsHex(password.getBytes());
        Account account = accountService.getAccount(username, md5pass);
        System.out.println(account);
        model.addAttribute("account",account);
        HttpSession session = req.getSession();
        session.setAttribute("account",account);
        System.out.println("wqkjehwjkqehjkeh+++");

        //获得输入的验证码值
        String value1 = vCode;
        //获取图片的值
        String value2 = (String) session.getAttribute("code");
        Boolean isSame = false;
        //对比两个值（字母不区分大小写）
        if (value2.equalsIgnoreCase(vCode)) {
            isSame = true;
        }

        System.out.println("username=" + username);
        //        List<Order> orderList = orderService.getOrdersByUsername(username);
        List<Order> orderList = orderService.getOrderList();
        System.out.println("id=" + orderList.get(0).getOrderId());
        model.addAttribute("orderList", orderList);
        session.setAttribute("orderList", orderList);

        Order order= orderService.getOrder(1151);
        order.setOrderId(0);
        order.setShipAddress1("null");
        order.setBillAddress1("null");
        order.setShipCountry("null");
        BigDecimal bigDecimal=new BigDecimal("0.00");
        order.setTotalPrice(bigDecimal);
        model.addAttribute("changeOrder",order);
        session.setAttribute("changeOrder",order);

        if (account == null || !isSame) {
            if (!isSame) {
                String tips = "Invalid Verification Code.   Signon failed.";
                model.addAttribute("message", tips);
            } else {
                String tips = "Invalid username or password.  Signon failed.";
                model.addAttribute("message", tips);
            }
            return "houtai/test";
        } else {
            account.setPassword(null);
            String tips = "";
            model.addAttribute("message", tips);
            model.addAttribute("account", account);
            session.setAttribute("account", account);
            System.out.println("进入系统主页面");
            return "houtai/general";
        }
    }

    //    删除order
    @RequestMapping("/deleteOrder")
    public String deleteOrder(int orderId, HttpServletRequest request, Model model) {
        System.out.println("删除order");
        HttpSession session = request.getSession();
        orderService.deleteOrderByOrderId(orderId);
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();

        List<Order> orderList = orderService.getOrderList();
        session.setAttribute("orderList", orderList);
        model.addAttribute("orderList", orderList);
        return "houtai/general";
    }

    //发货
//    删除order
    @RequestMapping("/deliverOrder")
    public String deliverOrder(int orderId, HttpServletRequest request, Model model) {
        System.out.println("发货");
        HttpSession session = request.getSession();
        String status = "D";
        Order order = orderService.getOrder(orderId);
        order.setStatus("D");
        orderService.updateOrderStatus(order);
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();

        List<Order> orderList = orderService.getOrderList();
        session.setAttribute("orderList", orderList);
        model.addAttribute("orderList", orderList);
        return "houtai/general";
    }

    //修改order
    @RequestMapping("/changeOrder")
    public String changeOrder(int orderId, HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        Order order = orderService.getOrder(orderId);
        orderService.updateOrderStatus(order);
        model.addAttribute("changeOrder", order);
        session.setAttribute("changeOrder", order);
        return "houtai/general";
    }

    //    搜索searchorder
    @GetMapping("/searchOrder")
    public String searchorder(@RequestParam("orderId") int orderId, HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        Order order = orderService.getOrder(orderId);
        if(order==null){
            model.addAttribute("errorSearch","Search failure!!");
            return "houtai/general";
        }
        orderService.updateOrderStatus(order);
        model.addAttribute("changeOrder", order);
        session.setAttribute("changeOrder", order);
        return "houtai/general";
    }

    @RequestMapping("/orderinfoChange")
    public String orderinfoChange(@RequestParam("orderId") int orderId, @RequestParam("shipAddress1") String shipAddress1,
                                  @RequestParam("shipCountry") String shipCountry, @RequestParam("billAddress1") String billAddress1,
                                  @RequestParam("totalPrice") String totaliPrice, HttpServletRequest request, Model model) {

        HttpSession session = request.getSession();
        Order order = orderService.getOrder(orderId);
        System.out.println("修改订单");
        order.setShipAddress1(shipAddress1);
        order.setShipCountry(shipCountry);
        order.setBillAddress1(billAddress1);
        BigDecimal totalPrice_ = new BigDecimal(totaliPrice);
        System.out.println(shipAddress1 + " " + shipCountry);
        order.setTotalPrice(totalPrice_);
        orderService.updateOrder(order);
        model.addAttribute("changeOrder", order);
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        List<Order> orderList = orderService.getOrderList();
        session.setAttribute("orderList", orderList);
        model.addAttribute("orderList", orderList);
        return "houtai/general";
    }

    //******************************************************************************************************

    @GetMapping("/insertAccount")
    public String insertAccount(Account account, String username, String password, String repeatedPassword, Model model) {

        System.out.println(account);
        System.out.println(repeatedPassword);

        if (username == null || password == null || repeatedPassword == null || username == "" || password == "" || repeatedPassword == "") {

            model.addAttribute("msg3", "请填好*内容");
        } else {
            if (!account.getPassword().equals(repeatedPassword)) {

                model.addAttribute("msg3", "密码不一致");
            } else {
                if (accountService.getAccount(account.getUsername(), account.getPassword()) != null) {

                    model.addAttribute("msg3", "该用户已存在，请更改账户名");
                } else {
                    accountService.insertAccount(account);

                    model.addAttribute("msg3", "增加用户成功");

                }
            }
        }

        model.addAttribute("AccountList", accountService.getAccountList());

        return "houtai/basic_form";

    }

    @GetMapping("/changeAccount")
    public String changeAccount(String username, Model model) {
        Account account = accountService.getAccount(username);


        model.addAttribute("Username", account.getUsername());
        model.addAttribute("PASSWORD", account.getPassword());
        System.out.println(account.getPassword()+"090909");
        model.addAttribute("email", account.getEmail());
        model.addAttribute("firstName", account.getFirstName());
        model.addAttribute("lastName", account.getLastName());
        model.addAttribute("status", account.getStatus());
        model.addAttribute("address1", account.getAddress1());
        model.addAttribute("address2", account.getAddress2());
        model.addAttribute("city", account.getCity());
        model.addAttribute("state", account.getState());
        model.addAttribute("zip", account.getZip());
        model.addAttribute("country", account.getCountry());
        model.addAttribute("phone", account.getPhone());
        model.addAttribute("favouriteCategoryId", account.getFavouriteCategoryId());
        model.addAttribute("languagePreference", account.getLanguagePreference());
        model.addAttribute("listOption", account.isListOption());
        model.addAttribute("bannerOption", account.isBannerOption());
        model.addAttribute("bannerName", account.getBannerName());

        model.addAttribute("AccountList", accountService.getAccountList());


        return "houtai/basic_form";
    }

    @GetMapping("/changeAccount2")
    public String changeAccount2(String username, String password, Account account, Model model) {


        System.out.println(username);

        System.out.println(password);
        System.out.println(account.getFirstName());
        System.out.println(account);

        if (username == null || password == null || username == "" || password == "") {
            model.addAttribute("msg", "请先选择用户再修改详细信息");
            model.addAttribute("AccountList", accountService.getAccountList());
            return "houtai/basic_form";
        } else {
            accountService.updateAccount(account);
            model.addAttribute("msg", "修改详细信息成功");
            model.addAttribute("AccountList", accountService.getAccountList());
            return "houtai/basic_form";

        }


    }


    @GetMapping("/updateAccount")
    public String updateAccount(String Username, String PASSWORD, String newpassword, Model model) {


        System.out.println(Username);
        System.out.println(PASSWORD);
        System.out.println(newpassword);
        Account account = accountService.getAccount(Username, PASSWORD);
        System.out.println(account);
        if (account == null) {
            model.addAttribute("msg", "选择要修改的用户");
            model.addAttribute("AccountList", accountService.getAccountList());
            return "houtai/basic_form";
        } else {
            if (newpassword == null || newpassword == "") {
                model.addAttribute("msg", "新输入密码不能为空");
                model.addAttribute("AccountList", accountService.getAccountList());
                model.addAttribute("Username", account.getUsername());
                model.addAttribute("PASSWORD", account.getPassword());


                System.out.println(account.getEmail());
                System.out.println(account.getFirstName());


                return "houtai/basic_form";

            } else {
                account.setPassword(newpassword);
                accountService.updateAccount(account);             //更新
                System.out.println("success");
                model.addAttribute("msg2", "修改密码成功！");

                model.addAttribute("AccountList", accountService.getAccountList());
                return "houtai/basic_form";
            }
        }


    }

    @GetMapping("/searchUser")
    public String searchUser(Account account, Model model) {
        System.out.println(account.getUsername() + account.getPassword());
        Account searchAccount = accountService.getAccount(account.getUsername(), account.getPassword());
        model.addAttribute("AccountList", searchAccount);

        return "houtai/basic_form";
    }
// *****************************************************************************************
@GetMapping("/dog")
public String dog(Model model){
    model.addAttribute("productList",catalogService.getProductListByCategory("DOGS"));
    return "houtai/productManage";
}
    @GetMapping("/fish")
    public String fish(Model model){
        model.addAttribute("productList",catalogService2.getProductListByCategory("FISH"));
        return "houtai/productManage";
    }
    @GetMapping("/cat")
    public String cat(Model model){
        model.addAttribute("productList",catalogService3.getProductListByCategory("CATS"));
        return "houtai/productManage";
    }
    @GetMapping("/bird")
    public String bird(Model model){
        model.addAttribute("productList",catalogService4.getProductListByCategory("BIRDS"));
        return "houtai/productManage";
    }
    @GetMapping("/searchresult")
    public String search(@RequestParam("q") String keyword,Model model){
        model.addAttribute("productList",catalogService.searchProductList(keyword));
        return "houtai/productManage";
    }
    @GetMapping("/update")
    public String item(String productid,Model model){
        System.out.println("xiugia item");
        model.addAttribute("itemList",catalogService.getItemListByProduct(productid));

        return "houtai/productManage";
    }
    @GetMapping("/add")
    public String add(String pname,String pid,String cate,String iid,String quantity,String listprice,String status,String attr,String descn,Model model){
        Product product = new Product();
        Category category = new Category();
        Item item = new Item();
        category.setCategoryId(cate);
        category.setDescription(descn);
        category.setName(pname);

        product.setName(pname);
        product.setProductId(pid);
        product.setCategoryId(cate);
        product.setDescription(descn);

        item.setItemId(iid);
        item.setQuantity(Integer.parseInt(quantity));
        item.setStatus(status);
        item.setListPrice(BigDecimal.valueOf(Long.parseLong(listprice)));
        item.setAttribute1(attr);
        item.setProductId(pid);

        catalogService.insertCategory(category);
        catalogService.insertProduct(product);
        catalogService.addItem(item);

        model.addAttribute("productList",catalogService.getProductListByCategory(cate));
        model.addAttribute("itemList",catalogService.getItemListByProduct(pid));
        return "houtai/productManage";
    }
    @GetMapping("/delete")
    public String delete(String productid,String cateid,Model model){
        System.out.println(productid);
        catalogService.deleteItemByProductId(productid);
        model.addAttribute("productList",catalogService.getProductListByCategory(cateid));
        return "houtai/productManage";
    }

    @GetMapping("/change")
    public String change(String itemid,String lp,String attr1,String s,String quan,String proid,Model model){
        Item item = new Item();
        item.setItemId(itemid);
        item.setAttribute1(attr1);
        BigDecimal bigDecimal=new BigDecimal(lp);
        item.setListPrice(bigDecimal);
        item.setStatus(s);
        item.setQuantity(Integer.parseInt(quan));
        catalogService.updateItem(item);
        model.addAttribute("productList",catalogService.getProductListByCategory("DOGS"));
        return "houtai/productManage";
    }
}